<template>
  <ContainerContent
    :loading="loading"
    :pagination="pagination"
    @run="handleRun">
    <template #header>
      <div>
        <a-date-picker
          v-model="endDate"
          show-time
          :allow-clear="false"
          format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="disabledDate"
          @change="handleDateRangePickerChange"
          class="w-200px">
          <template #extra>展示所选择时间点前十分钟的数据</template>
        </a-date-picker>
      </div>
      <div>
        <a-select
          v-model="nodeId"
          allow-search
          :style="{ width: '200px', height: '32px' }"
          placeholder="请选择节点"
          @change="handleRun">
          <a-option value="0">全部节点</a-option>
          <a-option v-for="item in nodeList" :key="item.id" :value="item.id">{{
            item.ip
          }}</a-option>
        </a-select>
      </div>

      <CloudFilterBar
        v-model="params"
        :run="handleRun"
        :schemes="filterSchemes"></CloudFilterBar>
      <a-button
        class="w-[30px]! h-[30px]! shrink-0 mr-[-16px]"
        @click="customize">
        <template #icon>
          <i-icons-li size="4" :spin="loading" />
        </template>
      </a-button>
    </template>
    <a-table
      ref="tableRef"
      v-bind="commonTableProps"
      :columns="columns"
      :scroll="scroll"
      :data="data"
      @sorter-change="onSorterChange">
      <template #rep_region="{ record }">
        <span>{{ record.ip }} ({{ record.rep_region }})</span>
      </template>
      <template #waf_id="{ record }">
        <span
          class="cursor-pointer text-blue-500 hover:underline"
          @click="openWafId(record)"
          >{{ record.waf_id }}</span
        >
      </template>
      <template #module="{ record }">
        <div v-if="record.module === 1" class="flex gap-x-1.5 items-center">
          自定义规则
        </div>
        <div v-else-if="record.module === 2" class="flex gap-x-1 items-center">
          速率限制
        </div>
        <div v-else-if="record.module === 3" class="flex gap-x-1 items-center">
          白名单
        </div>
      </template>
      <template #action="{ record }">
        <div v-if="record.action === 1" class="flex gap-x-1.5 items-center">
          <i-icons-prevent />
          阻止
        </div>
        <div v-if="record.action === 2" class="flex gap-x-1.5 items-center">
          <i-icons-skip />
          跳过
        </div>
        <div v-else-if="record.action === 3" class="flex gap-x-1 items-center">
          <i-icons-observe />
          观察
        </div>
      </template>
      <template #log>
        <i-icons-record
          class="cursor-pointer text-7 hover:text-1"
          @click="logVisible = true" />
      </template>
      <template #actions="{ record }">
        <a-link :hoverable="false" @click="handleDetailConfig(record)">
          详情
        </a-link>
        <!-- <a-link :hoverable="false" class="ml-4" @click="handleConfig(record)">
          调整策略
        </a-link> -->
      </template>
    </a-table>
    <CustomSorting v-model:visible="CustomVisible"></CustomSorting>
    <logDetails
      v-if="detailVisible"
      v-model:visible="detailVisible"
      :record="detailRecord"
      @refresh="run"></logDetails>
    <!-- <ApplyLog v-model:visible="logVisible"></ApplyLog> -->
    <!-- <adjust-strategy
      v-model:visible="adjustVisible"
      :record="adjRecord"
      @refresh="run" /> -->
  </ContainerContent>
</template>
<script lang="ts" setup>
import { getApiNodeWafLogApi } from '@/apis/modules/resolve/log'
import { getApiNodeSimpleApi } from '@/apis/modules/resolve/statistics'
import ContainerContent from '@/components/ContentContainer.vue'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import { useListRequest } from '@/hooks/useListRequest'
import { buildColumns } from '@/utils'
import { commonTableProps } from '@/utils/table'
import useTableColumn from './column'
// import AdjustStrategy from './components/AdjustStrategy.vue'
//import ApplyLog from './components/ApplyLog.vue'
import dayjs from 'dayjs'
import CustomSorting from './components/CustomSorting.vue'
import logDetails from './components/logDetails.vue'
const params = ref<CloudFilterBarState>({
  order: 'desc',
  sort: 'created_at',
  action: 0,
  module: 0,
  //id: '0',
  start_time: dayjs(
    dayjs().subtract(10, 'minute').format('YYYY-MM-DD HH:mm:ss')
  ).unix(),
  end_time: dayjs(dayjs().format('YYYY-MM-DD HH:mm:ss')).unix()
})

const scroll = {
  x: 1980
}

const nodeId = ref('0')
const startDate = ref(
  dayjs().subtract(10, 'minute').format('YYYY-MM-DD HH:mm:ss')
)
const handleRun = () => {
  startDate.value = dayjs(endDate.value)
    .subtract(10, 'minute')
    .format('YYYY-MM-DD HH:mm:ss')
  params.value.start_time = dayjs(startDate.value).unix()
  params.value.end_time = dayjs(endDate.value).unix()
  run({
    ...params.value,
    id: nodeId.value
  })
}
const endDate = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

const router = useRouter()
// const handleDateConfirm = () => {
//   params.value.start_time = startDate.value
//   params.value.end_time = endDate.value
//   run()
// }
const { visible: CustomVisible } = usePopup()
const { visible: logVisible } = usePopup()
const { visible: detailVisible, data: detailRecord } = usePopup()
// const { visible: adjustVisible, data: adjRecord } = usePopup()

// 时间选择示例
// const {
//   dates,
//   startTime,
//   endTime,
//   shortcuts,
//   disabledDate,
//   handleRangeDateSelect
// } = useRangeDate()

const { filterSchemes, columnsList } = useTableColumn()

const { data, loading, run, pagination } = useListRequest(getApiNodeWafLogApi, {
  params: params,
  immediate: false
})

const { createSortChange } = useTable(run, data)

const onSorterChange = createSortChange(params)
//配置
// const handleConfig = (record: any) => {
//   adjRecord.value = record
//   adjustVisible.value = true
// }

const openWafId = (record: any) => {
  localStorage.setItem('customRulesId', record.waf_id)
  //localStorage.setItem('logModule', record.module)
  if (record.module === 1) {
    router.push({
      name: 'NodeCustomRules'
    })
  } else if (record.module === 2) {
    router.push({
      name: 'NodeRateLimit'
    })
  } else if (record.module === 3) {
    router.push({
      name: 'NodeWhiteList'
    })
  }
}

//配置
const handleDetailConfig = (record: any) => {
  detailRecord.value = record
  detailVisible.value = true
  // router.push({
  //   name: 'SiteConfig',
  //   params: { current: 'abc.com' }
  // })
}

const nodeList = ref<any>([])

const customize = () => {
  CustomVisible.value = true
}

const disabledDate = (current: any) => {
  if (current && current > dayjs().endOf('day')) {
    return true
  }
  // 禁用30天之前的日期
  if (current && current < dayjs().subtract(30, 'day').startOf('day')) {
    return true
  }
  return false
}

const handleDateRangePickerChange = (val: string) => {
  startDate.value = dayjs(val)
    .subtract(10, 'minute')
    .format('YYYY-MM-DD HH:mm:ss')
  params.value.start_time = dayjs(startDate.value).unix()
  params.value.end_time = dayjs(endDate.value).unix()
  run({
    ...params.value,
    id: nodeId.value
  })
}

//获取区域
const getNodeList = () => {
  getApiNodeSimpleApi({}).then((res) => {
    nodeList.value = res || []
  })
}

const newList = ref([])
const columns = computed(() => buildColumns(newList.value))

onMounted(() => {
  const safeModule = localStorage.getItem('safeModule')
  if (safeModule) {
    //params.value.id = customRulesId
    params.value.module = Number(safeModule)
    localStorage.setItem('safeModule', '')
  }
  tableHeader()
  run()
  getNodeList()
})

watch(
  () => CustomVisible.value,
  () => {
    tableHeader()
  }
)

const tableHeader = () => {
  const NodeLogSort = localStorage.getItem('NodeLogSort')
  if (NodeLogSort) {
    const sortList = JSON.parse(NodeLogSort)
    const resultList = ref([])
    for (let i = 0; i < sortList.length; i++) {
      if (sortList[i].type === true) {
        const obj = columnsList.value.find((value) => {
          return value.dataIndex == sortList[i].key
        })
        resultList.value.push(obj)
      }
    }
    newList.value = resultList.value
  } else {
    newList.value = columnsList.value
  }
}
</script>
